package com.example.job.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.enums.ClassroomStatusEnum;
import com.example.job.domain.Classroom;
import com.example.job.mapper.ClassroomMapper;
import com.example.job.service.IClassroomService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;

@Component
@Slf4j
public class ClassroomXxlJob {

    @Autowired
    private ClassroomMapper classroomMapper;
    @Autowired
    private IClassroomService classroomService;

    @XxlJob("updateClassStatusHandler")
    public void updateClassStatusHandler() {
        log.info("updateClassStatusHandler开始");
        
        // 构建查询条件
        LambdaQueryWrapper<Classroom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Classroom::getStatus, ClassroomStatusEnum.SIGNING_UP.getCode())
                    .apply("DATE(start_date) = CURDATE()");  // 使用 MySQL 的 DATE 函数
        
        // 查询符合条件的教室
        List<Classroom> classrooms = classroomMapper.selectList(queryWrapper);
        
        if (!classrooms.isEmpty()) {
            // 更新状态为已开课
            for (Classroom classroom : classrooms) {
                classroom.setStatus(ClassroomStatusEnum.STARTED.getCode());
            }
            classroomService.batchUpdate(classrooms);
            log.info("成功更新{}个教室状态为已开课", classrooms.size());
        } else {
            log.info("没有需要更新状态的教室");
        }
        
        log.info("updateClassStatusHandler结束");
    }
}
